"""
Case Type   : MOT
Case Name   : MOT设置group_commit_size=2进行SQL语句测试
Create At   : 2021/1/7
Owner       : opentestcase001
Description :
    1、修改配置文件mot.conf中group_commit_size=2,重启数据库
    2、查看mot.conf配置文件参数是否生效,cat cluster/dn1/mot.conf |
    grep group_commit_size
    3、查看pg_log日志信息,cat cluster/../pg_log/xxx.log
    4、连接数据库,创建内存表，执行DML语句
    5、清理数据
Expect      :
    1、修改成功,重启数据库成功
    2、查看配置文件，参数修改生效
    3、查看日志，不存在参数无效信息
    4、连接数据库成功，创建内存表成功
    5、清理环境成功
History     :
    modified by opentestcase010 at 2023/2/6，优化MOT用例
"""

import os
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant


class MotParamTest(unittest.TestCase):

    def setUp(self):
        self.logger = Logger()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.user_node = Node('PrimaryDbUser')
        self.constant = Constant()
        self.commonsh = CommonSH
        self.common = Common()
        self.MOT_CONF = os.path.join(macro.DB_INSTANCE_PATH, 'mot.conf')
        self.MOT_LOG = os.path.join(macro.PG_LOG_PATH,
                                    macro.DN_NODE_NAME.split('/')[0])
        self.config_1 = 'enable_incremental_checkpoint'
        self.config_2 = 'group_commit_size = 2'
        self.mot_table = 't_mot_0115'
        self.logger.info(f'-----{os.path.basename(__file__)} start-----')
        self.logger.info('-----检查参数，修改配置，并重启数据库-----')
        show_msg = self.common.show_param(self.config_1)
        if 'off' not in show_msg:
            msg1 = self.primary_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'{self.config_1}=off')
            self.logger.info(msg1)
            msg2 = self.primary_sh.restart_db_cluster()
            self.logger.info(msg2)
            msg3 = self.primary_sh.get_db_cluster_status()
            self.assertTrue("Normal" or "Degrade" in msg3)
            show_msg = self.common.show_param(self.config_1)
            self.assertTrue('off' in show_msg)

    def test_mot_dump(self):
        text = '-----step1:修改mot.conf配置文件，设置group_commit_size=2,' \
               '重启数据库;expect:成功-----'
        self.logger.info(text)
        add_cmd = f'''source {macro.DB_ENV_PATH}
                    gs_ssh -c "echo -e '{self.config_2}' >> {self.MOT_CONF}" '''
        self.logger.info(add_cmd)
        add_res = self.user_node.sh(add_cmd).result()
        self.logger.info(add_res)
        self.assertIn('Successfully execute command on all nodes', add_res)
        self.primary_sh.restart_db_cluster()
        result = self.primary_sh.get_db_cluster_status()
        self.assertTrue("Normal" or "Degrade" in result)

        text = '-----step2:查看mot.conf文件参数修改是否生效;expect:已生效-----'
        self.logger.info(text)
        cat_cmd = f'''cat {self.MOT_CONF} | grep group_commit_size'''
        msg4 = self.user_node.sh(cat_cmd).result()
        self.logger.info(msg4)
        self.assertIn(self.config_2, msg4.split('\n')[-1].strip())

        text = '-----step3:查看pg_log日志;expect:不存在参数无效信息-----'
        self.logger.info(text)
        sql_cmd = f'''ls -t {self.MOT_LOG} | head -1'''
        self.logger.info(sql_cmd)
        log_msg = self.user_node.sh(sql_cmd).result()
        self.logger.info(log_msg)

        cat_cmd = f'''cd {self.MOT_LOG}
                      cat {log_msg} | grep group_commit_size'''
        self.logger.info(cat_cmd)
        cat_msg = self.user_node.sh(cat_cmd).result()
        self.logger.info(cat_msg)
        self.assertEqual('', cat_msg)

        text = '-----step4:连接数据库，创建内存表，执行DML操作;expect:成功-----'
        self.logger.info(text)
        sql_cmd = f'''
            drop foreign table if exists {self.mot_table};
            create foreign table {self.mot_table}(id int);
            insert into {self.mot_table}
                   values(generate_series(1,2000000));
            select count(*) from {self.mot_table};
            drop foreign table {self.mot_table} cascade;
            '''
        sql_msg = self.primary_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_msg)
        self.assertIn(self.constant.CREATE_FOREIGN_SUCCESS_MSG, sql_msg)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, sql_msg)
        self.assertIn('2000000', sql_msg)
        self.assertIn(self.constant.DROP_FOREIGN_SUCCESS_MSG, sql_msg)

        text = '-----step5:清理环境，删除参数;expect:成功-----'
        self.logger.info(text)
        del_cmd = f'''source {macro.DB_ENV_PATH};
                      sed -i '$d' {self.MOT_CONF}
                    '''
        self.logger.info(del_cmd)
        self.user_node.sh(del_cmd)
        cat_cmd = f'''cat {self.MOT_CONF} | grep group_commit_size'''
        msg5 = self.user_node.sh(cat_cmd).result()
        self.logger.info(msg5)

    def tearDown(self):
        self.logger.info('-----this is tearDown-----')
        self.logger.info('-----恢复配置，enable_incremental_checkpoint=on-----')
        show_msg = self.common.show_param(self.config_1)
        if 'on' not in show_msg:
            msg6 = self.primary_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'{self.config_1}=on')
            self.logger.info(msg6)
            msg7 = self.primary_sh.restart_db_cluster()
            self.logger.info(msg7)
            msg8 = self.primary_sh.get_db_cluster_status()
            self.assertTrue("Normal" or "Degrade" in msg8)
        show_msg = self.common.show_param(self.config_1)
        self.assertTrue('on' in show_msg)
        self.logger.info(f'-----{os.path.basename(__file__)} end-----')
